#!/bin/bash
HAS_ERROR=0
function DO_CMD() {
    echo Exec command: $@
    $@
    EXIT_CODE=$?
    if [ $EXIT_CODE != 0 ]; then
        HAS_ERROR=1
        echo ERROR: Execute $@ failed.
        exit $EXIT_CODE
    else
        echo FINE: Execute success.
    fi
}

function SUDO_CMD() {
    USER=$1
    shift
    echo "Exec command: su - '$USER' -c '$@'"
    eval "su - '$USER' -c '$@'"
    EXIT_CODE=$?
    if [ $EXIT_CODE != 0 ]; then
        HAS_ERROR=1
        echo ERROR: Execute $@ failed.
        exit $EXIT_CODE
    else
        echo FINE: Execute success.
    fi
}

#参数处理,全部用长参数
######################################
function parseOpts() {
    OPT_SPEC=":h-:"
    while getopts "$OPT_SPEC" optchar; do
        case "${optchar}" in
        -)
            case "${OPTARG}" in
            GRID_HOME)
                GRID_HOME="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            INVENTORY_LOCATION)
                INVENTORY_LOCATION="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            *)
                if [ "$OPTERR" = 1 ] && [ "${OPT_SPEC:0:1}" != ":" ]; then
                    echo "Unknown option --${OPTARG}" >&2
                fi
                ;;
            esac
            ;;
        h)
            usage
            exit 2
            ;;
        *)
            if [ "$OPTERR" != 1 ] || [ "${OPT_SPEC:0:1}" = ":" ]; then
                echo "Non-option argument: '-${OPTARG}'" >&2
            fi
            ;;
        esac
    done
}

parseOpts "$@"

if [ -z "$GRID_HOME" ]; then
    echo "ERROR: GRID_HOME not defined."
    echo "Usage: dbins-root --GRID_HOME <grid home> --INVENTORY_LOCATION <inventory dir>"
    exit 2
fi

if [ -z "$INVENTORY_LOCATION" ]; then
    INVENTORY_LOCATION=$(cat $GRID_HOME/oraInst.loc | grep inventory_loc | sed s'/inventory_loc\s*=\s*//' | sed s'/\s*$//')
fi

if [ -z "$INVENTORY_LOCATION" ]; then
    echo "ERROR: Can not determin invertory directory by file:$GRID_HOME/oraInst.loc."
    exit 3
fi

echo $INVENTORY_LOCATION/orainstRoot.sh
$INVENTORY_LOCATION/orainstRoot.sh
exitCode=$?
if [ $exitCode -ge 128 ]; then
    #负数返回码，大于127就是负数的补码
    echo "ERROR: Execute $INVENTORY_LOCATION/orainstRoot.sh failed, exitCode:$exitCode."
    exit $exitCode
elif [ $exitCode -gt 0 ]; then
    echo "WARN: Execute $INVENTORY_LOCATION/orainstRoot.sh has some warning, exitCode:$exitCode."
else
    echo "FINE: Execute $INVENTORY_LOCATION/orainstRoot.sh successful."
fi

echo $GRID_HOME/root.sh
OUT_TXT=$($GRID_HOME/root.sh)
exitCode=$?

#回显root脚本执行的日志文件内容
LOG_PATH=$(echo $OUT_TXT | cut -d' ' -f2)
if [ -f "$LOG_PATH" ]; then
    cat "$LOG_PATH"
fi

if [ $exitCode != 0 ]; then
    #负数返回码，大于127就是负数的补码
    echo "ERROR: Execute $GRID_HOME/root.sh failed, exitCode:$exitCode."
    exit $exitCode
else
    echo "FINE: Execute $GRID_HOME/root.sh successful."
fi
